const {LinValidator, Rule} = require('../../core/V');
const path = require('path');
const X = path.basename(module.filename, '.js');
const XModel = require('../model')[X];
const model_key_arr = Object.keys(XModel.rawAttributes).filter(key => !['createdAt', 'updatedAt', 'deletedAt'].includes(key));

class XValidator extends LinValidator {
}

Object.assign(XValidator.prototype, {Model: XModel}, model_key_arr.reduce((obj, key) => {
  obj[key] = [];
  return obj;
}, {}));

Object.assign(XValidator.prototype, {
  /** 默认所有模型上定义的字段都是required的,你可以使用$scene按情景筛选验证字段 */

  /** 覆盖id字段的验证规则,默认为required */
  id: [new Rule('isNumeric', '必须是数字')]

  /** 自定义验证方法*/
  /*vals {
      body: ctx.request.body,
      query: ctx.request.query,
      path: ctx.params,
      header: ctx.request.header
  }*/
  // , async validateXXX(vals) {
  //   throw new Error('xxx');
  // }

  , $scene: {
    post: model_key_arr.filter(key => key !== 'id').concat(['validateUniqueFields'])
    , put: ['id', 'validateRecordIfExist', 'validateUniqueFields'].concat(model_key_arr)
    , putOwn: ['id', 'validateRecordIfExist', 'validateUniqueFields', 'validateIsOwn'].concat(model_key_arr)
    , recordIfExist: ['id', 'validateRecordIfExist']
    , deleteOwn: ['id', 'validateIsOwn']
  }
});

module.exports = XValidator;
